// ConfigManager.java
package com.tidu.demo;

import java.io.*;
import java.util.*;
import java.util.regex.Pattern;

public class ConfigManager {
    private static final String CONFIG_FILE = "confidential_keywords.txt";

    /**
     * 获取默认的涉密关键词列表
     */
    public static List<String> getDefaultKeywords() {
        return Arrays.asList(
                "机密", "秘密", "绝密", "保密", "涉密",
                "内部资料", "内部文件", "不宜公开", "禁止外传", "保密期限"
        );
    }

    /**
     * 从配置文件加载用户自定义关键词
     */
    public static List<String> loadCustomKeywords() {
        List<String> keywords = new ArrayList<>();

        File configFile = new File(CONFIG_FILE);
        if (!configFile.exists()) {
            // 如果配置文件不存在，创建默认配置文件
            createDefaultConfigFile();
            return getDefaultKeywords();
        }

        // 使用UTF-8编码读取文件
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(configFile), "UTF-8"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (!line.isEmpty() && !line.startsWith("#")) {
                    keywords.add(line);
                }
            }
        } catch (IOException e) {
            System.err.println("读取配置文件出错，使用默认关键词: " + e.getMessage());
            return getDefaultKeywords();
        }

        return keywords.isEmpty() ? getDefaultKeywords() : keywords;
    }

    /**
     * 创建默认配置文件（使用UTF-8编码）
     */
    private static void createDefaultConfigFile() {
        try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(CONFIG_FILE), "UTF-8"))) {
            writer.println("# 保密文档关键词配置文件");
            writer.println("# 每行一个关键词，#开头的行会被忽略");
            writer.println();
            for (String keyword : getDefaultKeywords()) {
                writer.println(keyword);
            }
            System.out.println("已创建默认配置文件: " + CONFIG_FILE);
        } catch (IOException e) {
            System.err.println("创建默认配置文件失败: " + e.getMessage());
        }
    }

    /**
     * 根据关键词列表构建正则表达式模式
     */
    public static Pattern buildPattern(List<String> keywords) {
        StringBuilder patternBuilder = new StringBuilder("(?i)(");
        for (int i = 0; i < keywords.size(); i++) {
            if (i > 0) {
                patternBuilder.append("|");
            }
            patternBuilder.append(Pattern.quote(keywords.get(i)));
        }
//        patternBuilder.append("|<[^>]*>)"); // 保留占位符匹配
        patternBuilder.append(")"); // 保留占位符匹配
        return Pattern.compile(patternBuilder.toString());
    }
}
